import csv
import package.read_pdf as rp
import re
import pandas as pd
# 读取招商银行储蓄卡流水
def ZS_bank_tolist(file) :
    txt_list=[]
    with open(file, mode='r', encoding='utf-8-sig') as f:
        reader = csv.reader(f)
        for row in reader:
            if len(row) == 7:
                row_list = [str(col).strip() for col in row]
                money=""
                if row_list[2] == "":
                    money = f"-{str(row_list[3])}"
                else:
                    money = f"{str(row_list[2])}"
                row_list = [f"{str(row_list[0])[:4]}-{str(row_list[0])[4:6]}-{str(row_list[0])[6:]} {row_list[1]}", f"{row_list[5]}_{row_list[6]}", money]
                txt_list.append(row_list)
    # 关闭文件
    f.close()
    return txt_list[1:]
# 读取招商银行信用卡已出账流水
def ZS_credit_posted_tolist(file):
    # 读取pdf
    txt = rp.read_pdf_1(file)
    # 将文本按行分割
    txt_n = txt.split("\n")
    # 提取年份
    year = ""
    for index,row in enumerate(txt_n):
        if "账单日" in row:
            # 使用正则表达式获取date_txt中的日期，日期格式为****年**月**日
            year = str(re.search(r'\d{4}年\d{2}月\d{2}日', txt_n[index+1]).group()[:4])
            break
    # 提取交易流水
    txt_list=[]
    for index, row in enumerate(txt_n):
        # 去除首尾空格
        row = row.strip()
        # 按空格分割
        row_list = row.split(" ")
        # 如果前两列为日期，共6列，则记录为交易流水
        if len(row_list) == 6 and re.match(r'^\d{2}/\d{2}$', row_list[0]) and re.match(r'^\d{2}/\d{2}$', row_list[1]):
            txt_list.append(row_list)
    month_list1 = [str(row[0]).split("/")[0].strip() for row in txt_list]
    month_list2 = [str(row[1]).split("/")[0].strip() for row in txt_list]
    # print(month_list1)
    # print(month_list2)
    is_next_year_1 = "False"
    is_next_year_2 = "False"
    if "12" in month_list1:
        is_next_year_1 = "True"
    if "12" in month_list2:
        is_next_year_2 = "True"
    txt_list_new=[]
    for index,row in enumerate(txt_list):
        date1 = row[0].replace("/", "-")
        if is_next_year_1 == "True" and "01/" in date1:
            date1 = f"{str(int(year+1))}-{date1}"
        else:
            date1 = f"{year}-{date1}"
        date2= row[1].replace("/", "-")
        if is_next_year_2 == "True" and "01/" in date2:
            date2 = f"{str(int(year+1))}-{date2}"
        else:
            date2 = f"{year}-{date2}"
        txt_list_new.append([date1,row[2],row[3]])
    return txt_list_new
# 读取招商银行信用卡未入账流水
def ZS_credit_unposted_tolist(file_path:str):
    # 读取文件，并不将第一行作为列名
    data = pd.read_csv(file_path, header=None)
    # 提取数据中第一行作为列名（去除两端空格）
    columns = [str(column).strip() for column in data.iloc[0, :].tolist()]
    # 提取数据为列表
    data_list = [[str(column).strip() for column in row] for row in data.values[1:]]
    data_list = [[str(row[0]),str(row[2]),str(row[6])] for row in data_list]
    return data_list
